/**
 * ReturnNoteService.java
 * com.ebook.server.service
 * Copyright (c) 2013, 公司版权所有.
*/

package com.ebook.server.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 要返回的笔记关系service层
 * @author    潘吉友
 * @Date	 2013-7-2 	 
 */
@Service
public class ReturnNoteService {
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private static Log logger = LogFactory.getLog(ReturnNoteService.class);
	
	/**
	 * 更新某个设备的需要返回的笔记的状态
	 * <p>
	 * 判断是否存在，如果存在，则更新；否则插入
	 * @param noteid
	 * @param device_id 
	*/
	public void updateNoReturnData(String noteid,String device_id,int bookid){
		if(isExist(noteid, device_id)){
			updateReturnStatus(noteid, device_id, 1);
		}else{
			insert(noteid, device_id,bookid, 1);
		}
	}
	
	public void updateReturnData(String noteid,String device_id,int bookid){
		if(isExist(noteid, device_id)){
			updateReturnStatus(noteid, device_id, 0);
		}else{
			insert(noteid, device_id,bookid, 0);
		}
	}
	
	public void insert(String noteid,String device_id,int bookid,int noreturn){
		String sql = "insert into return_note (noteid,device_id,bookid,noreturn) values (?,?,?,?)";
		jdbcTemplate.update(sql, noteid,device_id,bookid,noreturn);
	}
	
	public void updateReturnStatus(String noteid,String device_id,int noreturn){
		String sql = "update return_note set noreturn=? where noteid=? and device_id=?";
		jdbcTemplate.update(sql, noreturn,noteid,device_id);
	}
	
	public boolean isExist(String noteid,String device_id){
		String sql = "select count(*) from return_note where noteid=? and device_id=?";
		if(jdbcTemplate.queryForInt(sql, noteid,device_id) > 0){
			return true;
		}
		return false;
	}

	public List<Map<String,Object>> queryByCnd(String device_id,int bookid){
		String sql = "select noteid from return_note where (device_id=? and bookid=? and noreturn=0) or (device_id!=? AND bookid=?)";
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql, device_id,bookid,device_id,bookid);
		if(list.isEmpty()){
			return null;
		}
		return list;
	}
	
	public void delByDeviceId(String device_id){
		String sql = "delete from return_note where device_id=?";
		jdbcTemplate.update(sql, device_id);
	}
	public void delete(String device_id,int bookid){
		String sql = "delete from return_note where device_id=? and bookid=?";
		jdbcTemplate.update(sql, device_id,bookid);
		
	}
}

